package cn.lg.soar.core.util;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.concurrent.Callable;

/**
 * @author luguoxiang 469599794@qq.com
 * @Date: 2025/5/18 11:01
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class CacheManagerUtils {

    private static CacheManager cacheManager;
    static {
        SoarSubscriber.subscribeInit((applicationContext -> {
            cacheManager = applicationContext.getBean(CacheManager.class);
        }));
    }

    /**
     * 读取缓存
     * @param cacheName 缓存名称
     * @param key 缓存key
     * @return
     */
    public static Object get(String cacheName, Object key) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            return null;
        }
        return cache.get(key);
    }

    /**
     * 读取缓存
     * @param cacheName 缓存名称
     * @param key 缓存key
     * @param supplier 加载数据
     * @return
     * @param <T>
     */
    public static <T>T get(String cacheName, Object key, Callable<T> supplier) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            try {
                return supplier.call();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return cache.get(key, supplier);
    }

    /**
     * 删除缓存
     * @param key 缓存key
     * @param cacheNames 缓存名称，必须填写，否则无效
     */
    public static void evict(Object key, String ...cacheNames) {
        for (String cacheName : cacheNames) {
            Cache cache = cacheManager.getCache(cacheName);
            if (cache != null) {
                cache.evict(key);
            }
        }
    }

    /**
     * 清空缓存
     * @param cacheNames 缓存名称，必须填写，否则无效
     */
    public static void clear(String ...cacheNames) {
        for (String cacheName : cacheNames) {
            Cache cache = cacheManager.getCache(cacheName);
            if (cache != null) {
                cache.clear();
            }
        }
    }

}
